<?php

namespace app\util\rke;

use app\common\service\face\FaceDevice;
use think\facade\Log;
use think\facade\Queue;
use app\model\AdminStaff;

/**
 * 人脸机数据处理
 */
class Aio extends AioBase
{
    private object $mq;

    public function __construct($mq)
    {
        $this->mq = $mq;
    }

    /**
     * 二维码开门
     * @param $info
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function qrPush($info)
    {
        $cache_key = "D_LOCKS:" . $info['QRCodeInfo']; // redis定义的key
        $openDoor = 0;
        $showInfo = '禁止通行!';
        $uid = getRedisCardReturnID($cache_key, '', true);
        if ($uid) {
            $openDoor = 1;
            $staffData = AdminStaff::field('name')->where('id', $uid)->find();
            if (!empty($staffData)) {
                $showInfo = $staffData['name'] . '<br>验证通过';
            } else {
                $showInfo = '验证通过';
            }
        }
        $sendData = [
            "operator" => "Unlock",
            "messageId" => $this->getMessageId(),
            "info" => [
                "uid" => $uid,
                "openDoor" => $openDoor,
                "showInfo" => $showInfo,
            ]
        ];
        $this->handlePublish($info['facesluiceId'], $sendData);
    }

    public function handleOnline($info)
    {
        $sendData = [
            "operator" => "Online-Ack",
            "messageId" => $this->getMessageId(),
            "info" => [
                "facesluiceId" => $info['facesluiceId'],
                "result" => "ok",
                "detail" => "",
            ]
        ];
        $this->handlePublish($info['facesluiceId'], $sendData);
        $this->handleDevice($info);
        FaceDevice::batchAllPerson($info['school_id']);
    }

    public function handleDevice($info)
    {
        $heart_time = strtotime($info['time']);
        $data = [
            'school_id' => $info['school_id'],
            'serial_type' => 2,
            'serial' => $info['facesluiceId'],
            'device_id' => $info['facesluiceId'],
            'heart_time' => $heart_time,
        ];
        if (!empty($info['ip'])) {
            $data['ip'] = $info['ip'];
        }
//        Log::error('接收人脸机心跳包');
//        Log::error($data);
        Queue::push('app\task\job\SchoolDevice@fire', $data);
        //时间校准
        $subTime = bcsub(time(), $heart_time, 0);
        if ($subTime > 30 || $subTime < -30) {
            $sendData = [
                "operator" => "SetSysTime",
                "messageId" => $this->getMessageId(),
                "info" => [
                    "facesluiceId" => $info['facesluiceId'],
                    "SysTime" => date('Y-m0d') . 'T' . date('H:i:s'),
                ]
            ];
            $this->handlePublish($info['facesluiceId'], $sendData);
        }
    }

    /**
     * 记录门禁开门记录
     * @param $result
     */
    public function handleAccessRecord($result)
    {
//        Log::error('加入队列->人脸机上传数据');
//        if ($result['info']['uid']) {
//            Queue::push('app\task\job\SchoolRkeRecord@fire', [
//                'serial' => $result['info']['facesluiceId'],
//                'card' => $result['messageId'],
//                'card_name' => Tool::$card_type[9],
//                'card_type' => 9,
//                'acs_res' => $result['info']['openDoor'],
//                'act_index' => 0,
//                'time' => time(),
//                'staff_id' => $result['info']['uid']
//            ]);
//        }
    }

    /**
     * 记录人脸机开门记录
     * @param $result
     */
    public function handleAccessFaceRecord($result)
    {
//        Log::error($result);
        if (!empty($result['info'])) {
            if ($result['info']['otype'] == '1') {
                //Log::error('加入队列->人脸机上传数据');
                Queue::push('app\task\job\SchoolRkeRecord@fire', [
                    'serial' => $result['info']['facesluiceId'],
                    'card' => dechex($result['info']['RFIDCard']),
                    'card_name' => Tool::$card_type[13],
                    'card_type' => 13,
                    'acs_res' => $result['info']['VerifyStatus'] == 1?1:0,
                    'act_index' => 0,
                    'time' => strtotime($result['info']['time']),
                    'staff_id' => $result['info']['customId'],
                    'school_id' => $result['info']['school_id'],
                    'face_similarity' => floor($result['info']['similarity1']),
                ]);
            }
            elseif ($result['info']['otype'] == '21') {
                //Log::error('加入队列->人脸机内置刷卡上传数据');
                Queue::push('app\task\job\SchoolRkeRecord@fire', [
                    'serial' => $result['info']['facesluiceId'],
                    'card' => dechex($result['info']['RFIDCard']),
                    'card_name' => Tool::$card_type[0],
                    'card_type' => 0,
                    'acs_res' => $result['info']['VerifyStatus'] == 1?1:0,
                    'act_index' => 0,
                    'time' => strtotime($result['info']['time']),
                    'staff_id' => $result['info']['customId'],
                    'school_id' => $result['info']['school_id'],
                    'face_similarity' => floor($result['info']['similarity1']),
                ]);
            }
        }
    }

    /**
     * 发送响应
     * @param $facesluiceId
     * @param $data
     * @param int $qos
     */
    protected function handlePublish($facesluiceId, $data, $qos = 0)
    {
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $this->mq->publish('mqtt/face/' . $facesluiceId, $data, ['qos' => $qos]);
    }
}